<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="培训标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入培训标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="关联试卷" prop="examId">
        <el-select v-model="form.examId" placeholder="请选择关联试卷" style="width: 240px;">
            <el-option
              v-for="item in examOptions"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          clearable
          v-model="queryParams.startTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择开始时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          clearable
          v-model="queryParams.endTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择结束时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:training:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:training:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:training:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:training:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="trainingList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="培训ID" align="center" prop="trainingId" />
      <el-table-column label="培训标题" align="center" prop="title" />
      <el-table-column label="培训说明" align="center" prop="description" />
      <el-table-column label="封面" align="center" width="120">
        <template #default="scope">
          <el-image
            style="
              width: 100px;
              height: 60px;
              display: flex;
              align-items: center;
            "
            v-if="scope.row.coverUrl"
            :src="scope.row.coverUrl"
            :preview-src-list="[scope.row.coverUrl]"
            fit="cover"
            hide-on-click-modal
            show-progress
            preview-teleported="true"
          >
          </el-image>
          <div
            v-else
            style="
              width: 100px;
              height: 60px;
              display: flex;
              justify-content: center;
              align-items: center;
            "
          >
            <el-icon :size="24"><icon-picture /></el-icon>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="关联试卷ID" align="center" prop="examId" />
      <el-table-column
        label="开始时间"
        align="center"
        prop="startTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="结束时间"
        align="center"
        prop="endTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:training:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:training:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改培训对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="trainingRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="培训标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入培训标题" />
        </el-form-item>
        <el-form-item label="培训说明" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <!-- <el-form-item label="封面URL" prop="coverUrl">
          <el-input v-model="form.coverUrl" placeholder="请输入封面URL" />
        </el-form-item> -->
        <!-- 修改封面URL表单项 -->
        <el-form-item label="培训封面" prop="coverUrl">
          <el-upload
            class="cover-uploader"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleCoverChange"
            :before-upload="beforeCoverUpload"
            accept="image/png, image/jpeg"
            v-if="form.trainingId"
          >
            <template #trigger>
              <div class="upload-area">
                <img
                  v-if="form.coverUrl"
                  :src="form.coverUrl"
                  class="cover-preview"
                />
                <el-icon v-else class="upload-icon"><Plus /></el-icon>
                <div class="upload-text">
                  {{ form.coverUrl ? "更换封面" : "点击上传" }}
                </div>
              </div>
            </template>
            <div class="tips">建议尺寸:不超过10MB</div>
          </el-upload>
          <div v-else>请先填写基本信息</div>
        </el-form-item>
        <el-form-item label="关联试卷" prop="examId">
          <el-select v-model="form.examId" placeholder="请选择关联试卷">
            <el-option
              v-for="item in examOptions"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            clearable
            v-model="form.startTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择开始时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            clearable
            v-model="form.endTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择结束时间"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Training">
import { Picture as IconPicture } from "@element-plus/icons-vue";
import {
  listTraining,
  getTraining,
  delTraining,
  addTraining,
  updateTraining,
  uploadTrainingImage,
} from "@/api/system/training";
import { listExam } from "@/api/system/exam";

const { proxy } = getCurrentInstance();

const trainingList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: null,
    description: null,
    coverUrl: null,
    examId: null,
    startTime: null,
    endTime: null,
    status: null,
  },
  rules: {
    title: [{ required: true, message: "培训标题不能为空", trigger: "blur" }],
    examId: [
      { required: true, message: "关联试卷ID不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询培训列表 */
function getList() {
  loading.value = true;
  listTraining(queryParams.value).then((response) => {
    trainingList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    trainingId: null,
    title: null,
    description: null,
    coverUrl: null,
    examId: null,
    startTime: null,
    endTime: null,
    status: null,
  };
  proxy.resetForm("trainingRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.trainingId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加培训";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _trainingId = row.trainingId || ids.value;
  getTraining(_trainingId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改培训";
  });
}

/** 提交按钮 */
// function submitForm() {
//   proxy.$refs["trainingRef"].validate((valid) => {
//     if (valid) {
//       if (form.value.trainingId != null) {
//         updateTraining(form.value).then((response) => {
//           proxy.$modal.msgSuccess("修改成功");
//           open.value = false;
//           getList();
//         });
//       } else {
//         addTraining(form.value).then((response) => {
//           proxy.$modal.msgSuccess("新增成功");
//           open.value = false;
//           getList();
//         });
//       }
//     }
//   });
// }

// 修改提交方法
const submitForm = () => {
  console.log("Form data before submission:", form.value);
  proxy.$refs["trainingRef"].validate(async (valid) => {
    if (valid) {
      try {
        // 先保存基础信息
        if (form.value.trainingId) {
          await updateTraining(form.value);
        } else {
          const res = await addTraining(form.value);
          // form.value.trainingId = res.data.trainingId; // 获取新建的ID
          console.log(res.data.trainingId);
        }

        // 如果有待上传的封面
        if (pendingCoverFile.value) {
          const { data } = await uploadTrainingImage(
            form.value.trainingId,
            pendingCoverFile.value
          );
          form.value.coverUrl = data;
        }

        proxy.$modal.msgSuccess("操作成功");
        open.value = false;
        getList();
      } catch (e) {
        proxy.$modal.msgError("操作失败：" + e.message);
      }
    }
  });
};

// 添加上传相关状态
const pendingCoverFile = ref(null);

// 修改上传处理逻辑
const handleCoverChange = (file) => {
  if (form.value.trainingId) {
    // 已有ID直接上传
    uploadTrainingImage(form.value.trainingId, file.raw)
      .then((res) => {
        form.value.coverUrl = res.data;
        proxy.$modal.msgSuccess("封面上传成功");
      })
      .catch((e) => {
        proxy.$modal.msgError("上传失败：" + e.message);
      });
  } else {
    // 暂存文件等待提交
    pendingCoverFile.value = file.raw;
    form.value.coverUrl = URL.createObjectURL(file.raw); // 本地预览
  }
};

/** 删除按钮操作 */
function handleDelete(row) {
  const _trainingIds = row.trainingId || ids.value;
  proxy.$modal
    .confirm('是否确认删除培训编号为"' + _trainingIds + '"的数据项？')
    .then(function () {
      return delTraining(_trainingIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/training/export",
    {
      ...queryParams.value,
    },
    `training_${new Date().getTime()}.xlsx`
  );
}

getList();

const handleCoverSuccess = (res) => {
  form.value.coverUrl = res.data;
  proxy.$modal.msgSuccess("封面上传成功");
};

const beforeCoverUpload = (rawFile) => {
  if (!["image/jpeg", "image/png"].includes(rawFile.type)) {
    proxy.$modal.msgError("只支持JPG/PNG格式!");
    return false;
  }
  if (rawFile.size / 1024 / 1024 > 10) {
    proxy.$modal.msgError("图片大小不能超过10MB!");
    return false;
  }
  return true;
};

const examOptions = ref([]);
function initExamOptions() {
  listExam().then((res) => {
    const { rows } = res;
    examOptions.value = rows.map((row) => ({
      label: row.examId,
      value: row.examId,
    }));
  });
}

initExamOptions();
</script>

<style scoped>
.cover-uploader {
  .upload-area {
    width: 240px;
    height: 135px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
      border-color: #409eff;
    }
  }
  .cover-preview {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  .upload-icon {
    font-size: 28px;
    color: #8c939d;
    position: absolute;
    left: 50%;
    top: 40%;
    transform: translate(-50%, -50%);
  }
  .upload-text {
    position: absolute;
    bottom: 10px;
    width: 100%;
    text-align: center;
    color: #666;
  }
  .tips {
    font-size: 12px;
    color: #999;
    margin-top: 8px;
  }
}
</style>
